package eu.dominicum.ft.ui.web.jsf.view.bean;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

/**
 * Backing bean for the authentication form.
 *
 * @author Harry Klerks
 * @since 2013M1
 */
@ManagedBean(name = "authentication")
@RequestScoped
public final class AuthenticationBean {

    private String username;
    private String password;

    public void login(ActionEvent event) {

        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        try {
            request.login(this.username, this.password);
        } catch (ServletException sex) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Aanmelden mislukt"));
        }
    }

    public void logout(ActionEvent event) {

        FacesContext facesContext = FacesContext.getCurrentInstance();
        Object request = facesContext.getExternalContext().getRequest();
        try {
            ((HttpServletRequest) request).logout();
        } catch (ServletException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}
